package cn.xerllent.wxtp.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;

import cn.hutool.core.util.ObjectUtil;
import cn.xerllent.common.service.impl.BaseServiceImpl;
import cn.xerllent.wxtp.entity.WxAdmin;
import cn.xerllent.wxtp.entity.WxCorp;
import cn.xerllent.wxtp.rest.SuiteController;
import cn.xerllent.wxtp.service.WxAdminService;
import cn.xerllent.wxtp.service.mapper.WxAdminMapper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpTpAdmin;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;

@Slf4j
@Service
//@AllArgsConstructor
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class WxAdminServiceImpl extends BaseServiceImpl<WxAdminMapper, WxAdmin>  implements WxAdminService {

	@Override
	public boolean isSuiteAdmin(WxAdmin wxAdmin) {
		QueryWrapper<WxAdmin> q = new QueryWrapper<>();
		if(ObjectUtil.isNotEmpty(wxAdmin.getCorpId())) {
			q.eq("corp_id", wxAdmin.getCorpId());
		}
		if(ObjectUtil.isNotEmpty(wxAdmin.getSuiteId())) {
			q.eq("suite_id", wxAdmin.getSuiteId());
		}
		if(ObjectUtil.isNotEmpty(wxAdmin.getAgentId())) {
			q.eq("agent_id", wxAdmin.getAgentId());
		}
		if(ObjectUtil.isNotEmpty(wxAdmin.getUserId())) {
			q.eq("user_id", wxAdmin.getUserId());
		}
		if(ObjectUtil.isNotEmpty(wxAdmin.getAuthType())) {
			q.eq("auth_type", wxAdmin.getAuthType());
		}
		q.last("LIMIT 1"); //应用多次安装agentId不一样，同一应用多个实例的情况存在！！One record is expected, but the query result is multiple records
		return ObjectUtil.isNotNull(getOne(q));
	}

	/**
	 * 同步应用管理员列表到本地数据库
	 * */
	@Override
	public void syncAdminList(final WxCpTpService wxCpTpService, final WxCorp corp) {
		//1.获取应用管理员
		try {
			WxCpTpAdmin wxCpTpAdmin = wxCpTpService.getAdminList(corp.getCorpId(), corp.getAgentId());
			List<WxAdmin> list = wxCpTpAdmin.getAdmin().stream().map(a ->{
				return new WxAdmin().setCorpId(corp.getCorpId()).setSuiteId(corp.getSuiteId()).setAgentId(corp.getAgentId()).setUserId(a.getUserId()).setAuthType(a.getAuthType());
			}).collect(Collectors.toList());
			remove(new LambdaUpdateWrapper<WxAdmin>().eq(WxAdmin::getCorpId, corp.getCorpId()).eq(WxAdmin::getAgentId, corp.getAgentId()));
			saveBatch(list);
		} catch (WxErrorException e) {
			log.debug("syncAdminList err:", e);
		}
	}

}
